package view;

import dao.DataManager;
import model.*;
import util.CinemaUtil;
import util.InputUtil;

import java.util.List;
import java.util.stream.Collectors;

public class AdminView {
    private final DataManager dataManager;
    private final User currentUser;

    public AdminView(User currentUser) {
        this.dataManager = DataManager.getInstance();
        this.currentUser = currentUser;
    }

    public void showMenu() {
        while (true) {
            System.out.println("\n===== 管理员菜单 =====");
            System.out.println("1. 密码管理");
            System.out.println("2. 用户管理");
            System.out.println("3. 退出登录");
            System.out.print("请选择操作: ");

            int choice = InputUtil.readIntRange("", 1, 3);

            switch (choice) {
                case 1:
                    showPasswordMenu();
                    break;
                case 2:
                    showUserMenu();
                    break;
                case 3:
                    System.out.println("已退出管理员账户");
                    return;
            }
        }
    }

    private void showPasswordMenu() {
        while (true) {
            System.out.println("\n===== 密码管理 =====");
            System.out.println("1. 修改自身密码");
            System.out.println("2. 重置非管理员用户密码");
            System.out.println("3. 返回上级菜单");
            System.out.print("请选择操作: ");

            int choice = InputUtil.readIntRange("", 1, 3);

            switch (choice) {
                case 1:
                    changeOwnPassword();
                    break;
                case 2:
                    resetUserPassword();
                    break;
                case 3:
                    return;
            }
        }
    }

    private void changeOwnPassword() {
        String oldPassword = InputUtil.readNonEmptyString("请输入当前密码: ");
        if (!oldPassword.equals(currentUser.getPassword())) {
            System.out.println("当前密码不正确，无法修改密码！");
            return;
        }

        String newPassword = InputUtil.readNonEmptyString("请输入新密码: ");
        String confirmPassword = InputUtil.readNonEmptyString("请再次输入新密码: ");

        if (!newPassword.equals(confirmPassword)) {
            System.out.println("两次输入的密码不一致，无法修改密码！");
            return;
        }

        currentUser.setPassword(newPassword);
        dataManager.updateUser(currentUser);

        CinemaUtil.addLog("修改管理员密码", currentUser.getUsername());
        System.out.println("密码修改成功！");
    }

    private void resetUserPassword() {
        List<User> users = dataManager.getAllUsers();
        List<User> nonAdminUsers = users.stream()
                .filter(user -> user.getUserType() != UserType.ADMIN)
                .collect(Collectors.toList());

        if (nonAdminUsers.isEmpty()) {
            System.out.println("没有非管理员用户可以重置密码！");
            return;
        }

        System.out.println("\n===== 用户列表 =====");
        CinemaUtil.printUsers(nonAdminUsers);

        String username = InputUtil.readNonEmptyString("请输入要重置密码的用户名: ");
        User userToReset = dataManager.getUserByUsername(username);

        if (userToReset == null) {
            System.out.println("未找到该用户！");
            return;
        }

        if (userToReset.getUserType() == UserType.ADMIN) {
            System.out.println("不能重置管理员用户密码！");
            return;
        }

        userToReset.setPassword("123456");
        userToReset.setNeedResetPassword(true);
        dataManager.updateUser(userToReset);

        CinemaUtil.addLog("重置" + userToReset.getUserType() + " " + username + "的密码", currentUser.getUsername());
        System.out.println("用户 " + username + " 的密码已重置为: 123456");
    }

    private void showUserMenu() {
        while (true) {
            System.out.println("\n===== 用户管理 =====");
            System.out.println("1. 列出所有用户");
            System.out.println("2. 添加用户");
            System.out.println("3. 删除用户");
            System.out.println("4. 查询用户");
            System.out.println("5. 修改用户信息");
            System.out.println("6. 返回上级菜单");
            System.out.print("请选择操作: ");

            int choice = InputUtil.readIntRange("", 1, 6);

            switch (choice) {
                case 1:
                    listAllUsers();
                    break;
                case 2:
                    addUser();
                    break;
                case 3:
                    deleteUser();
                    break;
                case 4:
                    searchUser();
                    break;
                case 5:
                    modifyUser();
                    break;
                case 6:
                    return;
            }
        }
    }

    private void listAllUsers() {
        System.out.println("\n===== 所有用户列表 =====");
        CinemaUtil.printUsers(dataManager.getAllUsers());
        InputUtil.pressEnterToContinue();
    }

    private void addUser() {
        System.out.println("\n===== 添加用户 =====");
        String id = CinemaUtil.generateUniqueId();
        String username = InputUtil.readNonEmptyString("请输入用户名: ");

        // 检查用户名是否已存在
        if (dataManager.getUserByUsername(username) != null) {
            System.out.println("用户名已存在，请使用其他用户名！");
            return;
        }

        System.out.println("请选择用户类型:");
        System.out.println("1. 管理员");
        System.out.println("2. 经理");
        System.out.println("3. 前台");
        int typeChoice = InputUtil.readIntRange("请选择: ", 1, 3);

        UserType userType;
        switch (typeChoice) {
            case 1:
                userType = UserType.ADMIN;
                break;
            case 2:
                userType = UserType.MANAGER;
                break;
            case 3:
                userType = UserType.FRONT_DESK;
                break;
            default:
                userType = UserType.FRONT_DESK;
        }

        String phoneNumber = InputUtil.readNonEmptyString("请输入手机号: ");

        // 检查手机号是否已被使用
        boolean phoneExists = dataManager.getAllUsers().stream()
                .anyMatch(u -> u.getPhoneNumber().equals(phoneNumber));

        if (phoneExists) {
            System.out.println("手机号已被使用，请使用其他手机号！");
            return;
        }

        // 创建用户
        User newUser = new User(id, username, "123456", userType, phoneNumber);
        newUser.setNeedResetPassword(true);

        dataManager.addUser(newUser);
        CinemaUtil.addLog("增加" + userType + " " + username, currentUser.getUsername());
        System.out.println("用户添加成功，默认密码为: 123456");
    }

    private void deleteUser() {
        System.out.println("\n===== 删除用户 =====");
        CinemaUtil.printUsers(dataManager.getAllUsers());

        String username = InputUtil.readNonEmptyString("请输入要删除的用户名: ");

        if (username.equals("admin")) {
            System.out.println("不能删除admin账户！");
            return;
        }

        User userToDelete = dataManager.getUserByUsername(username);
        if (userToDelete == null) {
            System.out.println("找不到该用户！");
            return;
        }

        boolean confirm = InputUtil.readBoolean("确定要删除用户 " + username + " 吗？此操作不可恢复！");
        if (!confirm) {
            System.out.println("操作已取消！");
            return;
        }

        dataManager.deleteUser(username);
        CinemaUtil.addLog("删除" + userToDelete.getUserType() + " " + username, currentUser.getUsername());
        System.out.println("用户 " + username + " 已成功删除");
    }

    private void searchUser() {
        System.out.println("\n===== 查询用户 =====");
        System.out.println("1. 按用户ID查询");
        System.out.println("2. 按用户名查询");
        System.out.println("3. 查询所有用户");

        int choice = InputUtil.readIntRange("请选择查询方式: ", 1, 3);

        switch (choice) {
            case 1:
                String id = InputUtil.readNonEmptyString("请输入用户ID: ");
                User userById = dataManager.getUserById(id);
                if (userById == null) {
                    System.out.println("未找到该用户！");
                } else {
                    System.out.println("\n===== 查询结果 =====");
                    System.out.println(userById);
                }
                break;
            case 2:
                String username = InputUtil.readNonEmptyString("请输入用户名: ");
                User userByName = dataManager.getUserByUsername(username);
                if (userByName == null) {
                    System.out.println("未找到该用户！");
                } else {
                    System.out.println("\n===== 查询结果 =====");
                    System.out.println(userByName);
                }
                break;
            case 3:
                listAllUsers();
                break;
        }

        InputUtil.pressEnterToContinue();
    }

    private void modifyUser() {
        System.out.println("\n===== 修改用户信息 =====");
        CinemaUtil.printUsers(dataManager.getAllUsers());

        String username = InputUtil.readNonEmptyString("请输入要修改的用户名: ");
        User userToModify = dataManager.getUserByUsername(username);

        if (userToModify == null) {
            System.out.println("找不到该用户！");
            return;
        }

        if (userToModify.getUserType() == UserType.ADMIN) {
            System.out.println("不能修改管理员用户信息！");
            return;
        }

        System.out.println("\n当前用户信息:");
        System.out.println(userToModify);

        // 修改用户类型
        System.out.println("\n是否修改用户类型? 当前类型: " + userToModify.getUserType());
        if (InputUtil.readBoolean("")) {
            System.out.println("请选择新的用户类型:");
            System.out.println("1. 经理");
            System.out.println("2. 前台");

            int typeChoice = InputUtil.readIntRange("请选择: ", 1, 2);
            UserType newType = typeChoice == 1 ? UserType.MANAGER : UserType.FRONT_DESK;
            userToModify.setUserType(newType);
        }

        // 修改手机号
        System.out.println("\n是否修改手机号? 当前手机号: " + userToModify.getPhoneNumber());
        if (InputUtil.readBoolean("")) {
            String newPhone = InputUtil.readNonEmptyString("请输入新的手机号: ");

            // 检查手机号是否已被其他用户使用
            boolean phoneExists = dataManager.getAllUsers().stream()
                    .filter(u -> !u.getUsername().equals(username))
                    .anyMatch(u -> u.getPhoneNumber().equals(newPhone));

            if (phoneExists) {
                System.out.println("手机号已被其他用户使用，无法修改！");
            } else {
                userToModify.setPhoneNumber(newPhone);
            }
        }

        dataManager.updateUser(userToModify);
        System.out.println("用户信息修改成功！");
    }
}
